

window.getRowByRowsId = function (rows, id) {
    const len = rows.length;
    for(var i = 0; i < len; i++) {
        const row = rows[i];
        if (row.id == id) return row;
    }
};
window.loadJs = function (url, callback) {
    const script = document.createElement('script');
    script.type = "text/javascript";
    if (typeof (callback) !== "undefined") {
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "compl" + "ete") {
                    script.onreadystatechange = null;
                    callback();
                }
            }
        } else {
            script.onload = function () {
                callback();
            }
        }
    }
    script.src = url;
    document.body.appendChild(script);
};
window.formatBytes = function (size) {
    if (typeof(size) !== 'number') return '';
    const units = ['Byte', 'KB', 'MB', 'GB', 'TB'];
    for (var i = 0; size >= 1024 && i < 4; i++) size /= 1024;
    return Math.round(size * 100) / 100 + '' + units[i];
}
window.str_replace = function (subtext, newtext, fulltext) {
    // 模仿PHP写的文本替换功能
    var i1 = 0;
    var i2 = 0;
    const arr = [];
    while (true) {
        i1 = fulltext.indexOf(subtext, i2);
        if (i1 === -1) {
            arr.push(fulltext.substr(i2));
            break;
        }
        arr.push(fulltext.substring(i2, i1));
        i2 = i1 + subtext.length;
    }
    return arr.join(newtext);
}
window.parseURL = function (url) {
    if (url === undefined) {
        url = window.location.href
    }
    const a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function () {
            const ret = {}
            const seg = a.search.replace(/^\?/, '').split('&')
            const len = seg.length
            for (var i = 0; i < len; i++) {
                if (!seg[i]) {
                    continue;
                }
                const s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/'),
        pathparts: (function () {
            return getPathparts(a.pathname);
        })()
    };
}
window.getPathparts = function (pathname) {
    const sign = '-'
    var path = sign + pathname + sign
    path = window.str_replace('/', sign, path)
    path = window.str_replace(sign + sign, sign, path)
    const ret = path.split(sign);
    for (var i = 0; i < ret.length; i++) {
        ret[i] = ret[i].split('.')[0]
    }
    return ret;
};
window.objCount = function (obj) {
    if (obj === undefined) {
        return 0;
    }
    if (typeof (obj) !== 'object') {
        return 0;
    }
    var i = 0;
    for (var k in obj) {
        if (k) {
            i++;
        }
    }
    return i;
}
window.clone = function (obj) {
    if (typeof obj !== 'object') {
        return obj;
    }
    if (obj === null) {
        return null;
    }
    var o;
    if (obj instanceof Array) {
        o = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            o.push(window.clone(obj[i]));
        }
    } else {
        o = {};
        for (var j in obj) {
            o[j] = window.clone(obj[j]);
        }
    }
    return o;
}
window.date = function (date) {
    function add0(m) {
        return m < 10 ? '0' + m : m;
    }
    if (date === undefined) {
        date = new Date();
    }
    const Y = date.getFullYear();
    const m = add0(date.getMonth() + 1);
    const d = add0(date.getDate());
    return Y + '-' + m + '-' + d;
}
window.datetime = function (date) {
    function add0(m) {
        return m < 10 ? '0' + m : m;
    }
    if (date === undefined) {
        date = new Date();
    }
    const Ymd = window.date(date);
    const H = add0(date.getHours());
    const i = add0(date.getMinutes());
    const s = add0(date.getSeconds());
    return Ymd + ' ' + H + ':' + i + ':' + s;
}
window.html_encode = function (str) {
    var s = '';
    if (str.length === 0)
        return '';
    s = str.replace(/&/g, '&gt;');
    s = s.replace(/</g, '&lt;');
    s = s.replace(/>/g, '&gt;');
    s = s.replace(/ /g, '&nbsp;');
    s = s.replace(/\\'/g, '&#39;');
    s = s.replace(/\\"/g, '&quot;');
    s = s.replace(/\r\n/g, '<br>');
    s = s.replace(/\r/g, '<br>');
    s = s.replace(/\n/g, '<br>');
    return s;
}
window.getHtmlByBBCode = function (str) {
    const reg = new RegExp('\\[([A-Z]+)\\:([a-z]+)(\\,([a-z]+)\\=([\\dA-Za-z\\.]+))*\\]');
    const result = str.replace(reg, function () {
        const args = arguments;
        const codePre = args[1];
        const codeType = args[2];
        if (codePre === 'CQ' && codeType === 'shake') {
            return window.getHtmlByCQCode_shake();
        }
        if (codePre === 'CQ' && codeType === 'face') {
            // return window.getHtmlByCQCode_face(args[5]);
            return str;
        }
        if (codePre === 'CQ' && codeType === 'image') {
            return window.getHtmlByCQCode_image(args[5]);
        }
        return str;
    });
    return result
}
window.getHtmlByCQCode_shake = function () {
    return '[shake震动]';
}
window.getHtmlByCQCode_face = function (id) {
    return '表情编号=' + id;
}
window.getHtmlByCQCode_image = function (file) {
    const baseURL = window.api.config('baseURL');
    var url = baseURL + '/public/message/image.php';
    url += '?filename=' + file;
    return '<a target=_blank href="' + url + '">图片</a>';
}
window.isMobile = function () {
    if (screen.width < screen.height)
        return true;
    const sUserAgent = navigator.userAgent.toLowerCase();
    const bIsIpad = /ipad/i.test(sUserAgent);
    const bIsIphoneOs = /iphone os/i.test(sUserAgent);
    const bIsMidp = /midp/i.test(sUserAgent);
    const bIsUc7 = /rv:1.2.3.4/i.test(sUserAgent);
    const bIsUc = /ucweb/i.test(sUserAgent);
    const bIsAndroid = /android/i.test(sUserAgent);
    const bIsCE = /windows ce/i.test(sUserAgent);
    const bIsWM = /windows mobile/i.test(sUserAgent);
    if ((bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM)) {
        return true;
    }
    return false;
}
window.isIE = function () {
    const sUserAgent = navigator.userAgent
    if (sUserAgent.indexOf('MSIE') >= 0) {
        return true;
    }
    if (sUserAgent.indexOf('Media Center') >= 0) {
        return true;
    }
    if (sUserAgent.indexOf('.NET') >= 0) {
        return true;
    }
    return false;
}
window.getParams = function () {
    var a = document.createElement('a');
    a.href = location.href;
    var ret = {},
    seg = a.search.replace(/^\?/,'').split('&'),
    len = seg.length, i = 0, s;
    for (;i<len;i++) {
        if (!seg[i]) { continue; }
        s = seg[i].split('=');
        ret[s[0]] = s[1];
    }
    return ret;
};
window.isEmpty = function (obj) {
    if (obj === undefined) return true;
    if (obj === null) return true;
    if (obj === '') return true;
    if (obj === NaN) return true;
    if (obj === 0) return true;
    if (obj === '0') return true;
    if (typeof(obj) === 'object') {
        for (var key in obj) {
            if(obj.hasOwnProperty(key)) return false;
        }
        return true;
    }
    return false;
};

const axios_configdefa = {

    // `method`是发出请求时使用的请求方法
    method: 'POST',

    // `baseURL`将被添加到`url`前面，除非`url`是绝对的。
    // 可以方便地为 axios 的实例设置`baseURL`，以便将相对 URL 传递给该实例的方法。
    baseURL: '',

    // `transformRequest`允许在请求数据发送到服务器之前对其进行更改
    // 这只适用于请求方法'PUT'，'POST'和'PATCH'
    // 数组中的最后一个函数必须返回一个字符串，一个 ArrayBuffer或一个 Stream
    transformRequest: [function (data) {
        // 做任何你想要的数据转换
        // https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js
        try {
            data = Qs.stringify(data, {arrayFormat: 'brackets'})
        } catch (e) {
            alert('transformRequest时发生错误：' + e);
        }
        return data;
    }],

    // `headers`是要发送的自定义 headers
    headers: {
        //'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded',
        //'Content-Type': 'application/json; charset=utf-8',
    },

    // `data`是要作为请求主体发送的数据
    // 仅适用于请求方法“PUT”，“POST”和“PATCH”
    // 当没有设置`transformRequest`时，必须是以下类型之一：
    // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    // - Browser only: FormData, File, Blob
    // - Node only: Stream
    data: {
        session: {
            id: (function () {
                if (!window.localStorage.hasOwnProperty('sessionId')) {
                    window.localStorage.sessionId = new Date().getTime() + Math.random().toString().substring(2);
                }
                return window.localStorage.sessionId;
            })(),
            email_id: window.localStorage.email_id,
            email_pwd: window.localStorage.email_pwd,
        }
    },

    // `timeout`指定请求超时之前的毫秒数。
    // 如果请求的时间超过'timeout'，请求将被中止。
    timeout: 10000,

    // `withCredentials`指示是否跨站点访问控制请求
    // should be made using credentials
    withCredentials: false, // default

    // “responseType”表示服务器将响应的数据类型
    // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    responseType: 'json', // default

};

const i18n = new VueI18n({
    locale: 'zh',
    messages: {
        'zh': {},
        'en': {}
    }
});
const CheckProperty = function (object, property) {
    if (object === undefined) return false;
    if (object === null) return false;
    if (typeof(object) !== 'object') return false;
    if (!object.hasOwnProperty(property)) return false;
    const value = object[property];
    if (value === null) return false;
    return true;
};

const alertMessage = function (message, go) {
    if (message === null) return;
    if (message === '') return;
    if (message.indexOf('您尚未登录本系统，请先登录。') >= 0) return;
    message = window.str_replace('<br />', "\r\n", message);
    alert(message);
    // 处理go
    if (typeof (go) === 'string') {
        const newhash = '#' + go + '.html';
        if (newhash === top.location.hash) {
            top.location.reload();
        } else {
            top.location.hash = newhash;
        }
    }
};

const VueInit = function (config) {
    const axios_config = window.clone(axios_configdefa);
    if (CheckProperty(config, 'axios')) {
        for (var key in config.axios) {
            axios_config[key] = config.axios[key];
        }
    }
    const vue = {};
    vue.directives = {};
    vue.directives.focus = {};
    vue.directives.focus.inserted = function (el, value) {
        console.log('vue.directives.focus.inserted', value);
        if (value) {
            el.focus();
        }
    };
    vue.i18n = i18n;
    vue.el = '#app';
    // vue.created = function () {
    // alert('vue.created');
    // };
    vue.data = {};
    vue.data.config = config;
    vue.data.form = {};
    vue.watch = {};

    vue.methods = {};
    vue.methods.ApiPost = function (_path, _param, additional_config) {
        if (typeof(_param) !== 'object') _param = {};
        if (window.localStorage.hasOwnProperty('wxcode')) {
            _param.wxcode = window.localStorage.wxcode;
        }
        var req_path = _path;
        var req_param = _param;
        if (CheckProperty(axios_config, 'reqJsonMode') && axios_config.reqJsonMode) {
            axios_config.transformRequest = null;
            if (axios_config.reqJsonMode >= 2) {
                axios_config.headers['Content-Type'] = 'application/json; charset=UTF-8';
            }
            req_path = '';
            req_param = {};
            req_param.path = _path;
            req_param.request = _param;
        }
        return new Promise(function (_promise_resolve, _promise_reject) {
            const promise_resolve = function (res) {
                return _promise_resolve(res);
            }
            const promise_reject = function (res, ex, title, beAlert) {
                if ((typeof res) !== 'object' || res === null) {
                    res = {}
                }
                if ((typeof ex) === 'string') {
                    ex = new Error(ex);
                }
                if ((typeof ex) === 'object' && ex !== null) {
                    res.message = ex.message;
                }
                if (typeof(res.message) === 'string') {
                    if (typeof(title) === 'string') {
                        res.message = '[' + title + ']' + res.message;
                    }
                    if (beAlert) alert(res.message);
                    console.log(title, res);
                }
                return _promise_reject(res);
            };
            for (var key in additional_config) {
                axios_config[key] = additional_config[key];
            }
            const axios1 = axios.create(axios_config);
            axios1.post(req_path, req_param).then(function (res) {
                if (!res.hasOwnProperty('status')) {
                    return promise_reject(res, 'no status in res', 'HTTP状态未知', true);
                }
                if (res.status !== 200) {
                    return promise_reject(res, 'res.status is ' + res.status, 'HTTP状态错误', true);
                }
                if (!res.hasOwnProperty('data')) {
                    return promise_reject(res, 'no data in res', 'HTTP无数据返回', true);
                }
                var res_data = res.data;
                if (res_data === null) {
                    return promise_reject(res, '服务器返回null', 'HTTP返回数据异常', true);
                }
                const res_data_type = typeof (res_data);
                if (res_data_type === 'object') {
                } else if (res_data_type === 'string') {
                    try {
                        res_data = JSON.parse(res_data);
                    } catch (ex) {
                        return promise_reject(res, ex, 'JSON解析错误', true);
                    }
                } else {
                    return promise_reject(res, 'res_data_type=' + res_data_type, '服务器返回未知格式', true);
                }
                // 处理localStorage
                if (res_data.hasOwnProperty('localStorage')) {
                    if (typeof (res_data.localStorage) === 'object') {
                        for (var storageName in res_data.localStorage) {
                            window.localStorage[storageName] = res_data.localStorage[storageName];
                        }
                    }
                }
                if (res_data.hasOwnProperty('message') && res_data.message != '') {
                    // 这里只是把服务端返回的消息显示出来而已，不做任何处理。
                    // window.$vuf.alert(res_data.message, null, res_data.hasOwnProperty('title') ? res_data.title : null)
                    alertMessage(res_data.message, res_data.go);
                } else
                if (res_data.hasOwnProperty('Message') && res_data.Message != '') {
                    alertMessage(res_data.message, res_data.go);
                }
                const code = res_data.hasOwnProperty('code') ? parseInt(res_data.code, 10) : 0;
                if (code === -444) {
                    top.location.href = '/';
                }
                if (code !== 0) {
                    return promise_reject(res, 'code=' + code, '服务端返回错误代码');
                }
                // 所有异常处理完毕，下面返回正确的代码。
                return promise_resolve(res);
            }, function (error) {
                if (error.message === 'Network Error') return;
                //console.log('触发了[promise]的[reject],发生在[common.js]里的[ApiPost]方法:', error);
                // 转发给用户发起的页面
                const response = error.hasOwnProperty('response') ? error.response : error;
                return promise_reject(response, error, 'promise_reject-axios错误', true);
            }).catch(function (error) {
                console.log('触发了[promise]的[catch],发生在[common.js]里的[ApiPost]方法:', error);
                alert('axios1-catch' + error);
            })
        })
    };

    return vue;
}
